package com.design.pattern.singleton;

import java.lang.reflect.Constructor;


/**
 * 使用枚举实现单例模式 优点:实现简单、枚举本身就是单例，
 * 由jvm从根本上提供保障!避免通过反射和反序列化的漏洞 缺点没有延迟加载
 *
 */
public enum EnumSingleton {

    INSTANCE;

    // 枚举能够绝对有效的防止实例化多次,和防止反射和序列化破解
    public void add() {
        System.out.println("add方法...");
    }

    @Override
    public String toString() {
        return "EnumSingleton{}";
    }

    public static void main(String[] args) throws Exception{

        EnumSingleton instance1 = EnumSingleton.INSTANCE;
        EnumSingleton instance2 = EnumSingleton.INSTANCE;
        System.out.println(instance1 == instance2);
        instance1.add();

        Constructor<EnumSingleton> declaredConstructor = EnumSingleton.class.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        EnumSingleton instance3 = declaredConstructor.newInstance();
        System.out.println(instance3 == instance1);

//        for (int i = 0; i < 300; i++) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    EnumSingleton instance = EnumSingleton.INSTANCE;
//                    System.out.println(Thread.currentThread().getName() + "," + instance);
//                }
//            }).start();
//        }

    }
}
